package com.note.service.view;

import com.note.dao.view.viewDao;
import com.note.dao.view.viewDaoImpl;
import com.note.pojo.Comment;
import com.note.pojo.notePageShow;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class viewServiceImpl implements viewService{
    @Override
    public List<notePageShow> getAllNotes() throws SQLException {
        viewDao v = new viewDaoImpl();
        List<notePageShow> allNotes = v.getAllNotes();
        return allNotes;
    }

    @Override
    public boolean addcomment(int noteId, String content, Timestamp createTime, String nickname, int parentId) throws SQLException {
        viewDao v = new viewDaoImpl();
        int i = v.addcomment(noteId, content, createTime, nickname, parentId);
        if (i>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public List<Comment> getAllComments(int noteId) throws SQLException {
        viewDao v = new viewDaoImpl();
        List<Comment> allComments = v.getAllComments(noteId);
        for (int i = 0; i < allComments.size(); i++) {
            int parentId = allComments.get(i).getParentId();
            if(parentId!=0){
                allComments.get(findIndex(allComments,parentId)).children.add(i);
            }
        }
        Queue<Integer> listChildren = new LinkedList<>();
        for (int i = 0; i < allComments.size(); i++) {
            if(allComments.get(i).getParentId()==0){
                List<Integer> list = new ArrayList<>();
                for (int j=0;j<allComments.get(i).children.size();j++){
                    listChildren.offer(allComments.get(i).children.get(j));
                }
                while(!listChildren.isEmpty()){
                    int t = listChildren.poll();
                    list.add(t);
                    for (int j=0;j<allComments.get(t).children.size();j++){
                        listChildren.offer(allComments.get(t).children.get(j));
                    }
                }
                allComments.get(i).children = list;
            }
        }
        return allComments;
    }
    public int findIndex(List<Comment> commentList, int id){
        for (int i = 0; i < commentList.size(); i++) {
            if(commentList.get(i).getId() == id)
                return i;
        }
        return 0;
    }
}
